class Solution {
public:
    vector<int> spiralOrder(vector<vector<int>>& matrix) {
        int m = matrix.size();
        int n = matrix[0].size();
        vector<int> result(m * n, 0);
        int index = 0;
        int startx = 0;
        int starty = 0;
        int loop = min(m, n) / 2;
        int mid = min(m, n) / 2;
        int offset = 1;
        while(loop --){
            int i = startx;
            int j = starty;
            
            for (;j < n - offset; j++){
                result[index++] = matrix[i][j];
            }
            
            for (;i < m - offset; i++){
                result[index++] = matrix[i][j];
            }
            
            for (;j > starty; j--){
                result[index++] = matrix[i][j];
            }
            
            for (;i > startx; i--){
                result[index++] = matrix[i][j];
            }

            startx++;
            starty++;
            offset++;
        }
        if (min(m, n) % 2){
            int remaining = abs(m - n) + 1;
            for (int i = 0; i < remaining; i++){
                result[index++] = n > m ? matrix[startx][starty++] : matrix[startx++][starty];
            }
        }
        return result;
    }
};